﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration;
using System.Net;
using System.IO;
using mshtml;
using System.Windows.Threading;
using System.Security.Principal;
using System.Security.Permissions;
using CSUACSelfElevation;
using System.Diagnostics;
using System.Windows;
using Microsoft.Win32;


namespace proxy4
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        #region UTILITIES

        Utility utilityEngine = new Utility();

        System.Windows.Forms.WebBrowser webbrowser2 = new System.Windows.Forms.WebBrowser();

        DispatcherTimer timer = new DispatcherTimer();

        // 系统托盘图标
        private System.Windows.Forms.NotifyIcon notifyIcon;

        infoWnd infoWindow = null;

        #endregion

        #region 网关操作

        // 网关连接
        private void IPGConnect(bool showMsg = true)
        {
            utilityEngine.ResetIEProxy();
            // 回调函数
            if (showMsg)
            {
                webbrowser2.DocumentCompleted -= webbrowser2_DocumentCompleted;
                webbrowser2.DocumentCompleted += webbrowser2_DocumentCompleted;
            }
            else
            {
                webbrowser2.DocumentCompleted -= webbrowser2_DocumentCompleted;
            }

            // 保存用户设置
            SaveConfig();
            try
            {
                webbrowser2.Navigate(new Uri("http://its.pku.edu.cn/ipgw/ipgw.ipgw?uid=" + Settings1.Default.IPGUsername + "&password=" + Settings1.Default.IPGPassword + "&&range=2&timeout=1&operation=connect"));
            }
            catch (WebException e)
            {
                MessageBox.Show(e.Message);
            }

            //SlideInfo();

        }

        // 断开全部连接
        private void IPGDiscAll(bool showMsg = true)
        {
            // 回调函数
            if (showMsg)
            {
                webbrowser2.DocumentCompleted -= webbrowser2_DocumentCompleted;
                webbrowser2.DocumentCompleted += webbrowser2_DocumentCompleted;
            }
            else
            {
                webbrowser2.DocumentCompleted -= webbrowser2_DocumentCompleted;
            }
            // 保存用户设置
            SaveConfig();
            try
            {
                webbrowser2.Navigate(new Uri("http://its.pku.edu.cn/ipgw/ipgw.ipgw?uid=" + Settings1.Default.IPGUsername + "&password=" + Settings1.Default.IPGPassword + "&&range=2&timeout=1&operation=disconnectall"));
            }
            catch (WebException e)
            {
                MessageBox.Show(e.Message);
            }

            //SlideInfo();
        }

        private void IPGResultCallback()
        {
            var doc = webbrowser2.Document;

            // 鼠标形状
            tabControl.Cursor = Cursors.Arrow;
            // 显示连接结果
            MessageBox.Show(doc.Body.InnerText.Trim());

        }

        #endregion

        #region APPLICATION ACTIONS

        private void MyClose()
        {
            // 保存设置
            SaveConfig();

            // 释放托盘图标
            notifyIcon.Dispose();

            Environment.Exit(0);
        }

        private void MyMinimize()
        {
            notifyIcon.BalloonTipText = "考拉上网助手仍在运行...";
            notifyIcon.BalloonTipTitle = "考拉说：";
            notifyIcon.ShowBalloonTip(5000);
            this.ShowInTaskbar = false;
            this.WindowState = System.Windows.WindowState.Minimized;
        }

        private void MyNormal()
        {
            this.ShowInTaskbar = true;
            this.Show();
            this.Activate();
            this.WindowState = System.Windows.WindowState.Normal;
        }

        #region CERNTERM User Actions

        private int Login()
        {
            return Login(Settings1.Default.Username, Settings1.Default.Password);
        }

        private int Login(String username, String password)
        {
            try
            {
                HttpWebRequest req = WebRequest.Create("http://cernterm.sinaapp.com/User/authenticate" + "/username/" + username + "/password/" + password) as HttpWebRequest;
                req.Timeout = 5000;
                StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
                string responseData = responseReader.ReadToEnd();

                if (responseData.Substring(0, 5) != "error"
                    && !responseData.StartsWith("404"))
                {
                    Settings1.Default.ProxyAddress = responseData.Trim();//PROXY ADDRESS//
                    //Settings1.Default.ProxyUserName = null; //PROXY USERNAME//
                    //Settings1.Default.ProxyPassword = null; // PROXY PASSWORD//

                    // close connection
                    req.GetResponse().GetResponseStream().Close();
                    responseReader.Close();
                    SlideMain();
                    // Update Background Image
                    updateBackground();
                    return 0;
                }
                else
                {
                    MessageBox.Show("登录错误\r\n请检查用户名密码");
                    // close connection
                    req.GetResponse().GetResponseStream().Close();
                    responseReader.Close();
                    return -1;
                }

                // close connection
                req.GetResponse().GetResponseStream().Close();
                responseReader.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "网络错误");
                return -1;
            }

        }

        #endregion

        #region Auto Connect

        int FSMPhase = 0;
        private void oneKeyFSM()
        {
            FSMPhase--;

            if (FSMPhase < 0)
                FSMPhase = 0;
            switch (FSMPhase)
            {
                case 20:
                    utilityEngine.ResetIEProxy();
                    break;
                case 19:    // Phase 1
                    tabControl.Cursor = Cursors.Wait;
                    //IPGDiscAll(false);
                    IPGDiscAll();
                    break;
                case 17:
                    //IPGConnect(false);
                    IPGConnect();
                    break;
                case 10:
                    Login();
                    break;
                case 2:
                    slideInfoAsync();
                    utilityEngine.SetIEProxy(Settings1.Default.ProxyAddress);
                    if (utilityEngine.TestCurrentProxy() > 0)
                    {
                        tabControl.Cursor = Cursors.Arrow;
                        MessageBox.Show("完成！");
                    }
                    else
                    {
                        tabControl.Cursor = Cursors.Arrow;
                        MessageBox.Show("连接出错，请重试");
                    }
                    break;
                default:
                    break;
            }
        }

        #endregion

        #region SlideTab

        private void SlideLogin()
        {
            // load user info
            LoadConfig();

            utilityEngine.ResetIEProxy();

            /*
            // 如果有已注册用户信息，则直接登录
            
            if (Settings1.Default.Username != "")
            {
                Login();
            }
            */

            tabControl.SelectedIndex = 0;
        }
        private void slideInfoAsync(){
            // load user info
            LoadConfig();

            // show InfoWnd Asynchronizely
            //if (infoWindow != null) infoWindow.Dispose();
            if (infoWindow == null) infoWindow = new infoWnd();
            infoWindow.parentWnd = this;
            infoWindow.AsynShow();
        }
        private void SlideInfo()
        {

            infoWindow = new infoWnd();
            infoWindow.parentWnd = this;
            infoWindow.AsynShow();
            /*
            this.Hide();
            if (infoWindow != null) infoWindow.Dispose();
            infoWindow = new infoWnd();
            infoWindow.ShowDialog();
            infoWindow.updateContent();
            updateBackground();
            this.Show();
            */
        }
        public void SlideInfoCallback()
        {
            try
            {
                infoWindow.ShowDialog();
            }
            catch { }
        }
        private void SlideMain()
        {
            // load user info
            LoadConfig();
            
            tabControl.SelectedIndex = 2;

        }
        private void SlideIPG()
        {
            // load user info
            LoadConfig();

            tabControl.SelectedIndex = 3;
        }
        private void SlideAbout()
        {
            tabControl.SelectedIndex = 4;
        }
        private void SlideWifi()
        {
            tabControl.SelectedIndex = 5;
        }
        private void SlideGallery()
        {
            tabControl.SelectedIndex = 6;
        }
        private void SlideOnekey()
        {
            // 判断是否符合一键登陆条件
            if (Settings1.Default.IPGPassword == "" || Settings1.Default.IPGUsername == "")
            {
                MessageBox.Show("网关登陆信息不全，无法使用一键登陆");
                SlideIPG();
                return;
            }
            if (!Settings1.Default.IPGRememberMe)
            {
                MessageBox.Show("未选择记住网关密码，无法使用一键登陆");
                SlideIPG();
                return;
            }
            if (Settings1.Default.Username == "" || Settings1.Default.Password == "")
            {
                MessageBox.Show("未设置用户名密码，无法使用一键登陆");
                SlideLogin();
                return;
            }
            tabControl.SelectedIndex = 7;
        }

        #endregion

        #region Gallery And Info Actions

        private void updateBackground()
        {
            try
            {
                using (BinaryReader reader = new BinaryReader(File.Open(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data\\bg.jpg"), FileMode.Open)))
                {

                    byte[] bytes = reader.ReadBytes((int)(new FileInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data\\bg.jpg"))).Length);
                    reader.Close();

                    BitmapImage bgImg = new BitmapImage();
                    bgImg.BeginInit();
                    bgImg.StreamSource = new MemoryStream(bytes);
                    bgImg.EndInit();

                    tabControl.Background = new ImageBrush(bgImg);


                }
            }
            catch( Exception e ){
                MessageBox.Show(e.Message);
            }
            try{
                HttpWebRequest req = WebRequest.Create("http://cernterm.sinaapp.com/Gallery/getBgURL") as HttpWebRequest;
                req.Timeout = 5000;
                StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
                string responseData = responseReader.ReadToEnd().Trim();

                if (responseData.Substring(0, 5) != "error")
                {
                    // load local image
                    string location = String.Format("file:///{0}/data/bg.jpg", Directory.GetCurrentDirectory());

                    bool fuckWPF1 = File.Exists(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data\\bg.jpg"));
                    int fuckWPF2 = (int)(new FileInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data\\bg.jpg")).Length);
                    try
                    {
                        // update image
                        using (WebClient client = new WebClient())
                        {
                            // data directory
                            if (!Directory.Exists("data")) Directory.CreateDirectory("data");
                            // update the HTML
                            client.DownloadFileAsync(new Uri(responseData), System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data\\bg.jpg"));
                        }
                    }catch
                    {
                    }

                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
            }
        }


        #endregion

        #endregion

        #region User Configuration

        private void LoadConfig()
        {
            // IPG rememeber password
            // IPG
            txtIPGUsername.Text = Settings1.Default.IPGUsername;
            txtIPGPassword.Password = Settings1.Default.IPGPassword;
            ckbIPGAutoLogon.IsChecked = Settings1.Default.IPGAutoLogin;
            //ckbIPGRememberMe.IsChecked = Settings1.Default.IPGRememberMe;
            // Cernterm User
            txtUsername.Text = Settings1.Default.Username;
            txtPassword.Password = Settings1.Default.Password;


        }

        private void SaveConfig()
        {
            // Get current settings
            // IPG
            Settings1.Default.IPGUsername = txtIPGUsername.Text;
            Settings1.Default.IPGPassword = txtIPGPassword.Password;
            //Settings1.Default.IPGRememberMe = ckbIPGRememberMe.IsChecked.HasValue ? ckbIPGRememberMe.IsChecked.Value : false;
            // Certerm User
            Settings1.Default.Username = txtUsername.Text;
            Settings1.Default.Password = txtPassword.Password;

            Settings1.Default.Save();
        }

        #endregion

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Label_MouseDown_1(object sender, MouseButtonEventArgs e)
        {
            System.Diagnostics.Process.Start("www.solesschong.com");
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            /* 
             * Control Setup
             */

            // Timer
            timer.IsEnabled = true;
            timer.Interval = TimeSpan.FromMilliseconds(500);
            timer.Tick += timer_Tick;

            // 系统托盘图标
            notifyIcon = new System.Windows.Forms.NotifyIcon();
            notifyIcon.Icon = new System.Drawing.Icon(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "default.ico"));
            notifyIcon.Visible = true;
            notifyIcon.BalloonTipText = "考拉上网助手正在运行...";
            notifyIcon.BalloonTipTitle = "考拉说：";
            notifyIcon.ShowBalloonTip(5000);

                // 托盘鼠标事件
            notifyIcon.Click += new EventHandler((o, evt) =>
            {
                if (this.WindowState != System.Windows.WindowState.Minimized)
                {
                    MyMinimize();
                }
                else
                {
                    MyNormal();
                }
            });

            // Suppress Script Error
            webbrowser2.ScriptErrorsSuppressed = true;

            // Button Context Menu: Left Button
            noseButton.Click += (obj, args) => { mainMenu.IsOpen = true; };

            // clear IE Proxy Setup
            utilityEngine.ResetIEProxy();

            // Info Page
            // SlideInfo();

            // ask for userdata
            if (Settings1.Default.firstStartup == true)
            {
                var userdataWnd = new UserdataWnd();
                userdataWnd.ShowDialog();
                if (Login() == 0)
                    MessageBox.Show("欢迎使用考拉上网助手！\r\n考拉可以帮助你获取更快更好的网络接入。\r\n更多选项请点击考拉的鼻子");
            }
            else
            {
                /*
                 * Configuration
                 */
                LoadConfig();

                // switch to Info tab
                SlideOnekey();

            }

            // Update background from disk
            try
            {
                using (BinaryReader reader = new BinaryReader(File.Open(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data\\bg.jpg"), FileMode.Open)))
                {

                    byte[] bytes = reader.ReadBytes((int)(new FileInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data\\bg.jpg"))).Length);
                    reader.Close();

                    BitmapImage bgImg = new BitmapImage();
                    bgImg.BeginInit();
                    bgImg.StreamSource = new MemoryStream(bytes);
                    bgImg.EndInit();

                    tabControl.Background = new ImageBrush(bgImg);


                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
            

            Settings1.Default.firstStartup = false;

        }

        void timer_Tick(object sender, EventArgs e)
        {
            oneKeyFSM();
        }

        void webbrowser2_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            IPGResultCallback();
            throw new NotImplementedException();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://cernterm.sinaapp.com/Index/registerpage");
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            utilityEngine.ResetIEProxy();
            System.Diagnostics.Process.Start("http://its.pku.edu.cn");
        }

        // 按钮“上网走你”
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            utilityEngine.SetIEProxy(Settings1.Default.ProxyAddress);
            // if (utilityEngine.TestCurrentProxy() > 0)
            {
                notifyIcon.BalloonTipText = "已经加载代理，可以加速访问国外网。";
                notifyIcon.BalloonTipTitle = "考拉说：";
                notifyIcon.ShowBalloonTip(5000);

                MessageBox.Show("完成！");

                // 资讯页面
                SlideInfo();
            }
            /*
            else
            {
                MessageBox.Show("连接出错，请重试");
            }
             * */

        }
        // 按钮“卸载代理”
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            notifyIcon.BalloonTipText = "已经卸载代理，适合访问国内网。";
            notifyIcon.BalloonTipTitle = "考拉说：";
            notifyIcon.ShowBalloonTip(5000);

            utilityEngine.ResetIEProxy();
            MessageBox.Show("完成！");
        }


        // 注册用户
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            Button_Click_1(sender, e);
        }

        private void Window_MouseDown_1(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
                this.DragMove();
        }

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            MyClose();
        }

        private void Border_Initialized_1(object sender, EventArgs e)
        {
            // 左键菜单
            this.mainMenu.ContextMenu = null;
        }

        private void Border_MouseUp_1(object sender, MouseButtonEventArgs e)
        {
            // 
            this.ContextMenu.PlacementTarget = this.mainMenu;
            this.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
            this.ContextMenu.IsOpen = true;
        }

        // 用户登陆
        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            SlideLogin();
        }

        // Wifi
        private void MenuItem_Click_4(object sender, RoutedEventArgs e)
        {
            SlideWifi();
        }

        // 资讯
        private void MenuItem_Click_5(object sender, RoutedEventArgs e)
        {
            SlideInfo();
        }

        // 网关登陆
        private void MenuItem_Click_6(object sender, RoutedEventArgs e)
        {
            utilityEngine.ResetIEProxy();
            SlideIPG();
        }

        // 主界面
        private void MenuItem_Click_7(object sender, RoutedEventArgs e)
        {
            SlideMain();
        }

        private void ckbIPGAutoLogon_Checked(object sender, RoutedEventArgs e)
        {
//            MessageBox.Show("注意：勾选此项，每次运行软件都会自动断开全部连接并连接网关，您在其他终端的网关连接会被终中断");
        }

        // 按钮：断开全部
        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            utilityEngine.ResetIEProxy();
            IPGDiscAll();
        }

        // 按钮：登录
        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            utilityEngine.ResetIEProxy();
            tabControl.Cursor = Cursors.Wait;
            IPGConnect();
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            SaveConfig();
            Login();
        }

        // 一键操作
        private void Button_Click_8(object sender, RoutedEventArgs e)
        {
//            Login();
            /*
             * version 2.0
             */
            // start the FSM
            FSMPhase = 21;

            /*
             * Version 1.0 
             * 
            // 登录网关
                // 断开网关
            IPGDiscAll();
            System.Threading.Thread.Sleep(3000);
                // 登录
            IPGConnect();
            System.Threading.Thread.Sleep(6000);
            // 登录CernTerm
            Login();
            // 加速
            utilityEngine.SetIEProxy(Settings1.Default.ProxyAddress);
            // 提示
            if (utilityEngine.TestCurrentProxy() > 0)
            {
                MessageBox.Show("完成！");
            }
            else
            {
                MessageBox.Show("连接出错，请重试");
            }
             * */
        }

        private void txtIPGUsername_LostFocus(object sender, RoutedEventArgs e)
        {
            Settings1.Default.IPGUsername = txtIPGUsername.Text;
        }

        private void txtIPGPassword_LostFocus(object sender, RoutedEventArgs e)
        {
            Settings1.Default.IPGPassword = txtIPGPassword.Password;
        }

        private void noseButton_MouseEnter(object sender, MouseEventArgs e)
        {
            var dropShadowEffect = new System.Windows.Media.Effects.DropShadowEffect();
            dropShadowEffect.ShadowDepth = 0;
            dropShadowEffect.BlurRadius = 30;
            dropShadowEffect.Color = Colors.Brown;

            noseButton.Effect = dropShadowEffect;
        }

        private void noseButton_MouseLeave(object sender, MouseEventArgs e)
        {
            var dropShadowEffect = new System.Windows.Media.Effects.DropShadowEffect();
            dropShadowEffect.ShadowDepth = 0;
            dropShadowEffect.BlurRadius = 0;

            noseButton.Effect = dropShadowEffect;
        }

        private void Button_Click_12(object sender, RoutedEventArgs e)
        {
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.UseShellExecute = true;
            proc.WorkingDirectory = Environment.CurrentDirectory;
            proc.FileName = "WifiConsole.exe";
            proc.Arguments = "s " + txtWifiSSID.Text + " " + txtWifiKey.Text;
            proc.Verb = "runas";
            proc.WindowStyle = ProcessWindowStyle.Hidden;

            try
            {
                Process.Start(proc);
            }
            catch (Exception exc)
            {
                // The user refused the elevation.
                // Do nothing and return directly ...
                MessageBox.Show(exc.Message);
                return;
            }

        }

        private void btnWifiEnd_Click(object sender, RoutedEventArgs e)
        {
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.UseShellExecute = true;
            proc.WorkingDirectory = Environment.CurrentDirectory;
            proc.FileName = "WifiConsole.exe";
            proc.Arguments = "stop " + txtWifiSSID.Text + " " + txtWifiKey.Text;
            proc.Verb = "runas";
            //proc.WindowStyle = ProcessWindowStyle.Hidden;

            try
            {
                Process.Start(proc);
            }
            catch (Exception exc)
            {
                // The user refused the elevation.
                // Do nothing and return directly ...
                MessageBox.Show(exc.Message);
                return;
            }
        }

        private void MenuItem_Click_8(object sender, RoutedEventArgs e)
        {
            MyMinimize();
        }

        private void Button_Click_9(object sender, RoutedEventArgs e)
        {
            SlideInfo();
        }

        private void MenuItem_Click_9(object sender, System.Windows.RoutedEventArgs e)
        {
            if (mItemRunAtStart.IsChecked)
                utilityEngine.RunAtStart(true);
            else
                utilityEngine.RunAtStart(false);
        }

        private void MenuItem_Click_10(object sender, System.Windows.RoutedEventArgs e)
        {
            (new UserdataWnd()).ShowDialog();
            Login();
        }

        private void Button_Click_10(object sender, System.Windows.RoutedEventArgs e)
        {
            MessageBox.Show(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
        }

        private void MenuItem_Click_11(object sender, System.Windows.RoutedEventArgs e)
        {
            SlideAbout();
        }


    }
}
